
import QtQuick 2.2
import QtQuick.Controls 1.2
import QtQuick.Controls.Styles 1.2
import QtQuick.Layouts 1.0
import QtQuick.Dialogs 1.2
import QtQuick.Window 2.1

import org.microcsource.code 1.0

import "content"

ApplicationWindow {
    id: root
    visible: true
    height: 700
    title: "Annoide"
    width: 500

    //color: "#fcfcff"
    //color: "#f9f3e7"
    property string darkEditColor: "#fdf0d8";
    property string lightEditColor: "#fbf8f2";

    Rectangle {
        anchors.fill: parent;
        color: "#ffffff";
        antialiasing: true;
    }

    AboutDialog {
        id: aboutDialog
    }

    CompileDialog {
        id: compiler
    }

    WidentifyDialog {
        id: widentifyDialog
    }

    DocumentManager {
        id: document
        target: editor
        cursorPosition: editor.cursorPosition
        selectionStart: editor.selectionStart
        selectionEnd: editor.selectionEnd

        // initialize() loads the start file
        Component.onCompleted: {
            fileUrl = document.spinFile()
            status.text = document.shortFileName(fileUrl)
            status.text = fileUrl
            document.setUserPath(document.filePathName(fileUrl))
            document.fileUrl = fileUrl
            document.setSpinFile(fileUrl)
        }
/*
        onFontSizeChanged: fontSizeSpinBox.value = document.fontSize
        onFontFamilyChanged: {
            var index = Qt.fontFamilies().indexOf(document.fontFamily)
            if (index < 0) {
                fontFamilyComboBox.currentIndex = 0
                fontFamilyComboBox.special = true
            } else {
                fontFamilyComboBox.currentIndex = index
                fontFamilyComboBox.special = false
            }
        }
*/
    }

    WidentifyManager {
        id: widentify
        hostAddr: "Host Address"
    }

    FileDialog {
        id: openDialog
        title: "Open Spin File"
        //filter: "Spin files (*.spin);;All (*)"
        nameFilters: ["Spin files (*.spin)", "All (*)"]
        selectExisting: true
        onAccepted: {
            status.text = document.shortFileName(fileUrl)
            status.text = fileUrl
            document.setFileUrl(fileUrl)
        }
    }

    Action {
        id: newAction
        text: "New"
        shortcut: StandardKey.New
        onTriggered: {
            document.text = "\n";
            status.text = "Untitled";
            document.setSpinFile("");
        }
    }

    Action {
        id: openAction
        text: "Open"
        shortcut: StandardKey.Open
        iconSource: "images/ic_openfile72.png"
        onTriggered: {
            status.text = document.fileUrl;
            openDialog.folder = document.filePathName(document.fileUrl);
            openDialog.open();
        }
        tooltip: "Open a file"
    }

    Action {
        id: quitAction
        text: "Quit"
        onTriggered: Qt.quit()
    }

    Action {
        id: copyAction
        text: "Copy"
        shortcut: StandardKey.Copy
        iconName: "edit-copy"
        enabled: (!!activeFocusItem && !!activeFocusItem["copy"])
        onTriggered: activeFocusItem.copy()
    }
    Action {
        id: cutAction
        text: "Cut"
        shortcut: StandardKey.Cut
        iconName: "edit-cut"
        enabled: (!!activeFocusItem && !!activeFocusItem["cut"])
        onTriggered: activeFocusItem.cut()
    }
    Action {
        id: pasteAction
        text: "Paste"
        shortcut: StandardKey.Paste
        iconName: "edit-paste"
        enabled: (!!activeFocusItem && !!activeFocusItem["paste"])
        onTriggered: activeFocusItem.paste()
    }
    Action {
        id: debugAction
        text: "Debug"
        iconName: "images/ic_debug"
        onTriggered: {
            status.text = document.fileUrl;
            document.text = editor.text;
            document.saveFileUrl(document.fileUrl);
            document.compile(document.fileUrl);

            //status.text = document.fileUrl;
            //document.setFileUrl(document.fileUrl)

            if(document.status !== "") {
                compiler.open("Compile Error", "Program Has Errors", document.status);
            } else {
                compiler.open("Compile Ok", "Program Compiled Successfully", "");
            }
        }
    }

    Action {
        id: aboutAction
        text: "About"
        onTriggered: {
            aboutDialog.open();
        }
    }

    Action {
        id: widentifyAction
        text: "WiFi-Identify"
        onTriggered: {
            widentifyDialog.show(widentify.hostAddr);
        }
    }

    toolBar: ToolBar {
        id: toolbar

        anchors.top: parent.top
        anchors.left: parent.left
        anchors.right: parent.right

        property int btnSize: 80
        property int btnRadius: 5
        height: btnSize

        Rectangle {
            anchors.fill: parent;
            color: lightEditColor
        }

        Flow {
            id: toolFlow
            ToolButton {
                height: toolbar.btnSize
                width: toolbar.btnSize
                action: quitAction
                Accessible.name: "Quit"
                iconSource: "images/ic_exit72.png"
                tooltip: "Quit app"
            }

            ToolButton {
                height: toolbar.btnSize
                width: toolbar.btnSize
                action: aboutAction
                Accessible.name: "About"
                iconSource: "images/ic_about72.png"
                tooltip: "About Program"
            }

            ToolButton {
                height: toolbar.btnSize
                width: toolbar.btnSize
                action: openAction
                iconSource: "images/ic_openfile72.png"
                tooltip: "Open a file"
            }
            /*
            ToolButton {
                height: toolbar.btnSize
                width: toolbar.btnSize
                action: widentifyAction
                Accessible.name: "WiFi-Identify"
                iconSource: "images/ic_wifi72.png"
                tooltip: "WiFi-Identify"
            }
            */
            ToolButton {
                height: toolbar.btnSize
                width: toolbar.btnSize
                action: debugAction
                Accessible.name: "Debug"
                iconSource: "images/ic_debug72.png"
                tooltip: "Run program"
            }
        }
    }

    menuBar: MenuBar {
        Menu {
            title: "Edit"
            MenuItem { action: copyAction }
            MenuItem { action: cutAction }
            MenuItem { action: pasteAction }
            //MenuItem { action: findAction }
            //MenuItem { action: replaceAction }
        }
        Menu {
            title: "Help"
            MenuItem { action: aboutAction }
        }
    }

    Rectangle {
        id: background;
        anchors.fill: parent;
        color: lightEditColor
        radius: 3;
        gradient: Gradient {
            GradientStop {
                position: 0.00;
                color: darkEditColor
            }
            GradientStop {
                position: 1.00;
                color: lightEditColor
            }
        }
        antialiasing: true;
        border {
            width: 1;
            color: "#3d3dbb"
        }
    }

    Flickable {
        id: flick
        anchors.fill: parent
        contentHeight: editor.paintedHeight
        contentWidth: editor.paintedWidth
        clip: true

        function ensureVisible(r) {
            var rx = r.x;
            var ry = r.y;
            var cx = contentX;
            var cy = contentY;
            var rb = r.y+r.height;
            var bottom = height-statusBar.height;

            if(r.x <= editor.textMargin)
                cx = 0;

            if (cx >= r.x)
                cx = r.x;
            else if (cx+width <= r.x+r.width)
                cx = r.x+r.width-width;
            if (cy >= r.y)
                cy = r.y;
            else if (cy+height <= rb)
                cy = r.y-r.height-height;

            if (rb > bottom)
                cy = rb-height+statusBar.height;

            contentX = cx
            contentY = cy
        }

        TextEdit {
            /* The text editor. */
            id: editor
            anchors.fill: parent
            color: "#3d3dd3"
            focus: true
            font.family: "Parallax"
            font.pixelSize: 20
            text: document.text
            textFormat: TextEdit.PlainText
            textMargin: 5

            onCursorRectangleChanged: {
                flick.ensureVisible(cursorRectangle)
            }
            Keys.onPressed: {
                var r = cursorRectangle
                var rx = r.x
                var ry = r.y
                var cp = cursorPosition
                var ep = editor.positionAt(rx,ry)
                flick.ensureVisible(r)
            }

            MouseArea {
                property string drag: ""
                anchors.fill: parent

                onPressAndHold: {
                    if (editor.state == "") {
                        editor.cursorPosition = editor.positionAt(mouse.x+x,mouse.y+y);
                        editor.selectWord();
                        editor.state = "selection"
                        flick.ensureVisible(editor.cursorRectangle)
                    }
                    status.text = "onPressAndHold "+ mouse.x +" "+ mouse.y;
                }

                onClicked: {
                    if (editor.state == "") {
                        editor.cursorPosition = editor.positionAt(mouse.x+x,mouse.y+y);
                        if (!editor.focus)
                            editor.focus = true;
                    }
                    else {
                        editor.state = ""
                        editor.cursorPosition = editor.positionAt(mouse.x+x,mouse.y+y);
                    }
                    status.text = "onClicked "+ mouse.x +" "+ mouse.y;
                    flick.ensureVisible(editor.cursorRectangle)
                }

                onReleased: {
                    if (editor.state == "selection") {
                        if (drag == "selection") {
                            editor.state = "menu"
                        }
                        drag = ""
                    }
                    flick.interactive = true
                    status.text = "onReleased "+ mouse.x +" "+ mouse.y;
                }

                onPositionChanged: {
                    if (editor.state == "selection" && drag != "") {
                        if (drag == "start") {
                            var pos = editor.positionAt(mouse.x+x+startHandle.width/2,mouse.y+y);
                            var e = editor.selectionEnd;
                            if (e < pos)
                                e = pos;
                            editor.select(pos,e);
                        } else if (drag == "end") {
                            var pos = editor.positionAt(mouse.x+x-endHandle.width/2,mouse.y+y);
                            var s = editor.selectionStart;
                            if (s > pos)
                                s = pos;
                            editor.select(s,pos);
                        }
                    }
                    status.text = "onPositionChanged "+ mouse.x +" "+ mouse.y;
                }
            }
        }
    }

    StatusBar {
        id: statusBar
        height: 30
        anchors.right: parent.right
        anchors.rightMargin: 0
        anchors.left: parent.left
        anchors.leftMargin: 0
        anchors.bottom: parent.bottom
        anchors.bottomMargin: 0

        Rectangle {
            anchors.fill: parent;
            color: "#fcfcff"
            antialiasing: true;
        }

        Text {
            id: status
            text: "Welcome.spin"
            font.pixelSize: 14
        }
    }


}
